<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\AuthorizationsResouect;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use App\Http\Requests\Api\AuthorizationsRequest;
use App\Models\UserInfo;


class AuthorizationsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AuthorizationsRequest $request)
    {
        $code = $request->code;

        $miniProgram = \EasyWeChat::miniProgram(); // 小程序
        $data = $miniProgram->auth->session($code);

        // 如果结果错误，说明 code 已过期或不正确，返回 401 错误
        if (isset($data['errcode'])) {
            throw new AuthorizationException('Code 不正确');
        }

        // 找到 openid 对应的用户
        $user = User::with('userinfo')->where('weixin_openid',$data['openid'])->first();


        // 未找到对应用户则需要提交用户名密码进行用户绑定
        if (!$user){
            $user = \DB::transaction(function() use ($request, $data){
                $users = User::create([
                    'name'          =>  $request->userInfo['nickName'],
                    'weixin_openid' =>  $data['openid'],
                    'weixin_session_key'   =>  $data['session_key'],
                ]);

                $newInfo = array_merge($request->userInfo , ['user_id'=>$users->id]);
                $users->userinfo()->create($newInfo);

                return $users;
            });
        }

        $token = auth('api')->login($user);
        return self::respondWithToken($token)->setStatusCode(200);
    }


    /***
     * 刷新 TOKEN
     * @return \Illuminate\Http\JsonResponse|object 刷新 TOKEN
     */
    public function refreshToken()
    {
        $token = auth('api')->refresh();
        return self::respondWithToken($token)->setStatusCode(200);
    }


    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token'  =>  $token,
            'token_type'    =>  'Bearer',
            'expired_at'    =>  10
            //'expired_at'    =>  auth('api')->factory()->getTTL() * 60
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}
